/**
 * Author:  LiShibin.
 * Date:    2016/9/9.
 * File：   .
 */

/**
 * 深拷贝
 * @param {Object} 被复制的对象
 * @param {Object} 目标对象,默认为空对象
 * @return {Object}}
 */
function clone (obj, target) {
  target = target || {}
  for (var i in obj) {
    if (typeof obj[i] === 'object') {
      target[i] = (obj[i].constructor === Array) ? [] : {}
      clone(obj[i], target[i])
    } else {
      target[i] = obj[i]
    }
  }
  return target
}
/**
 * 从数组中移除一个对象
 * @param arr 数组对象
 * @param field 移除的字段匹配
 * @param text 匹配的值
 * @return {Boolean}
 */
function arrayRemoveOne (arr, field, text) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i][field] === text) {
      arr.splice(i, 1)
      return true
    }
  }
  return false
}

/**
 * 判断对象是否为空对象
 * @param e 判断对象
 * @returns {boolean}
 */
function isEmptyObject (e) {
  // vue 框架给数组添加了一个$remove的方法，所以对数组单独判断
  if (e instanceof Array) {
    if (e.length > 0) {
      return false
    } else {
      return true
    }
  }
  for (var t in e) {
    return false
  }
  return true
}

/**
 * 触发点击事件
 * @param element
 */
function clickElement (element) {
  // console.log('hello')
  // console.log(typeof  element)
  if (typeof element === 'string') {
    element = document.getElementById(element)
  }
  console.log(navigator.userAgent)
  var e = document.createEvent('MouseEvents')
  e.initEvent('click', true, true)
  element.dispatchEvent(e)
  if (getDeviceType() === 'iPhone') {
    // ios需要再触发click才能生效
    element.click()
  }
}

/**
 * 锁定
 * @param element 要锁定的dom
 * @param timeOut 锁定时间，默认1秒
 * @return {boolean} 是否在锁定状态中
 */
function freeze (element, timeOut) {
  timeOut = timeOut || 1000
  if (typeof element === 'string') {
    element = document.getElementById(element)
  }
  let freezeFlag = element.getAttribute('freeze-flag') // 是否锁定中
  let freezeFlagCountdown = element.getAttribute('freeze-flag-countdown') // 是否已经开始倒计时解锁中
  if (freezeFlag) {
    if (!freezeFlagCountdown) {
      element.setAttribute('freeze-flag-countdown', 'true') // 开始倒计时
      setTimeout(() => { // 倒计时结束
        element.removeAttribute('freeze-flag-countdown')
        element.removeAttribute('freeze-flag')
      }, timeOut)
    }
    return true
  } else {
    element.setAttribute('freeze-flag', 'true')
    if (!freezeFlagCountdown) {
      element.setAttribute('freeze-flag-countdown', 'true') // 开始倒计时
      setTimeout(() => { // 倒计时结束
        element.removeAttribute('freeze-flag-countdown')
        element.removeAttribute('freeze-flag')
      }, timeOut)
    }
    return false
  }
}
/**
 * 获取设备类型
 * @return string 'Android'or'iPhone or'Windows'or'unknown'
 */
function getDeviceType () {
  var agent = navigator.userAgent
  var device = ''
  if (agent.indexOf('Android') !== -1) {
    device = 'Android'
  } else if (agent.indexOf('iPhone') !== -1) {
    device = 'iPhone'
  } else if (agent.indexOf('Windows') !== -1) {
    device = 'Windows'
  } else {
    device = 'unknown'
  }
  return device
}
/**
 * 压缩图片
 * @param file 图片文件
 * @param fileSize 图片文件的大小
 * @callBack 压缩完成后的回调函数，参数：(base64)
 */
function compress (file, callBack) {
  var img = new window.Image()
  // 最大宽度
  var maxW = 640
  // 压缩比
  var compressRate = 0.6

  img.onload = function () {
    var cvs = document.createElement('canvas')
    var ctx = cvs.getContext('2d')

    if (img.width > maxW) {
      img.height *= maxW / img.width
      img.width = maxW
    }
    cvs.width = img.width
    cvs.height = img.height
    ctx.clearRect(0, 0, cvs.width, cvs.height)
    ctx.drawImage(img, 0, 0, img.width, img.height)

    var dataUrl = cvs.toDataURL('image/jpeg', compressRate)
    if (typeof callBack === 'function') {
      callBack(dataUrl)
    }
  }

  img.src = file
}
/**
 * 冷却，防止快速重复点击
 * @param element 要冷却的节点
 * @param coolingTime 冷却时间（ms），默认为1000(ms)
 */
function coolingElement (element, coolingTime) {
  coolingTime = coolingTime || 1000
  if (typeof element === 'string') {
    element = document.getElementById(element)
  }
  element.disabled = true
  setTimeout(function () {
    element.disabled = false
  }, coolingTime)
}

/**
 * 初始化百度地图对象
 * @param key 百度密钥
 * @returns {Promise} 异步对象
 */
function initMap (key) {
  return new Promise((resolve, reject) => {
    var script = document.createElement('script')
    script.type = 'text/javascript'
    script.src = 'http://api.map.baidu.com/getscript?v=2.0&ak=' + key + '&services=&t=' + (new Date()).getTime()
    script.onload = (event) => {
      resolve(window.BMap, event)
    }
    script.onerror = (error) => {
      reject(error)
    }
    document.head.appendChild(script)
  })
}
/**
 * 直接获取定位对象
 * @returns {Promise}
 */
function getLocal () {
  return new Promise((resolve, reject) => {
    initMap('tzAcIFZ5xCoRwm63NcBGfoVB').then(BMap => {
      var getLocation = new BMap.Geolocation()
      var geocoder = new BMap.Geocoder()
      getLocation.getCurrentPosition(function (cp) {
        geocoder.getLocation(cp.point, function (cl) {
          var options = cl.addressComponents
          options.point = cl.point
          resolve(options)
        })
      }, function (e) {
        console.log('getCurrentPosition失败：')
        console.log(e)
      })
    }, e => {
      console.log('initMap失败：')
      console.log(e)
    })
  })
}
/**
 * 字符串转bool
 * @param str
 * @returns {boolean}
 */
function strToBool (str) {
  if (typeof str === 'boolean') {
    return str
  } else if (typeof str === 'string') {
    return str === 'true'
  } else {
    return false
  }
}

function getNowFormatDate () {
  var date = new Date()
  var seperator1 = '-'
  var seperator2 = ':'
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var strDate = date.getDate()
  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()

  if (month >= 1 && month <= 9) {
    month = '0' + month
  }
  if (strDate >= 0 && strDate <= 9) {
    strDate = '0' + strDate
  }
  if (hour >= 0 && hour <= 9) {
    hour = '0' + hour
  }
  if (minute >= 0 && minute <= 9) {
    minute = '0' + minute
  }
  if (second >= 0 && second <= 9) {
    second = '0' + second
  }
  var currentdate = year + seperator1 + month + seperator1 + strDate + ' ' + hour + seperator2 + minute + seperator2 + second
  return currentdate
}
function getQueryString (name) {
  var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)')
  var r = window.location.search.substr(1).match(reg)
  if (r != null) {
    return unescape(r[2])
  }
  return null
}
/***
 * 节流函数 在wait间隔时间内不再进行任何调用时，触发一次最后的调用（如:wait设置为300ms，一直点击，该函数一直不执行，只有在间隔了300ms不做任何点击后，才执行刚才的最后一次点击）
 * @param func 执行函数
 * @param wait 等待时间
 * @param {Boolean} immediate 是否立即执行
 * @return {Function}
 */
function throttle (func, wait, immediate) {
  var timeout
  return function () {
    let context = this
    let args = arguments
    let later = function () {
      timeout = null
      if (!immediate) func.apply(context, args)
    }
    let callNow = immediate && !timeout
    clearTimeout(timeout)
    timeout = setTimeout(later, wait)
    if (callNow) func.apply(context, args)
  }
}
/***
 * 节流函数2 连续调用，每隔wait时间后触发一次（如:wait设置为300ms，一直点击，每隔300ms执行一次当前点击）
 * @param func 执行函数
 * @param wait 等待时间
 * @param {Boolean} immediate 是否立即执行
 * @return {Function}
 */
function throttle2 (func, wait, immediate) {
  var timeout
  return function () {
    let context = this
    let args = arguments
    let later = function () {
      timeout = null
      if (!immediate) func.apply(context, args)
    }
    let callNow = immediate && !timeout
    if (!timeout) {
      timeout = setTimeout(later, wait)
    }
    if (callNow) func.apply(context, args)
  }
}

/**
 * base64数据转为Blob
 * @param {String} base64数据
 * @return {Object} Blob
 */
function dataURLtoBlob (base64Data) {
  let tmp = base64Data.split(',')
  if (tmp.length === 2) { // 如果base64包含头部的话，去掉base64的头
    tmp.shift()
  }
  var bytes = window.atob(tmp) // 转换为byte
  // 处理异常,将ascii码小于0的转换为大于0
  var ab = new ArrayBuffer(bytes.length)
  var ia = new Uint8Array(ab)
  for (var i = 0; i < bytes.length; i++) {
    ia[i] = bytes.charCodeAt(i)
  }
  return new window.Blob([ab], {type: 'application/octet-stream'})
}

// // 获取附件图标
// function getAttachmentIcon (fileName) {
//   // 不带后缀名的文件，直接返回默认图标
//   if (!fileName.indexOf('.')) {
//     return require('./assets/images/app_what.png')
//   }
//   let fileIcon
//   let fileExt = fileName.split('.')[1].toLowerCase()
//   switch (fileExt) {
//     case 'apk':
//       fileIcon = require('./assets/images/app_apk.png')
//       break
//     case 'doc':
//     case 'docx':
//       fileIcon = require('./assets/images/app_doc.png')
//       break
//     case 'png':
//     case 'jpg':
//     case 'jpeg':
//     case 'gif':
//     case 'pdg':
//     case 'ai':
//       fileIcon = require('./assets/images/app_img.png')
//       break
//     case 'pdf':
//       fileIcon = require('./assets/images/app_pdf.png')
//       break
//     case 'ppt':
//       fileIcon = require('./assets/images/app_ppt.png')
//       break
//     case 'rar':
//       fileIcon = require('./assets/images/app_rar.png')
//       break
//     case 'txt':
//       fileIcon = require('./assets/images/app_txt.png')
//       break
//     case 'vedio':
//       fileIcon = require('./assets/images/app_vedio.png')
//       break
//     case 'xls':
//     case 'xlsx':
//       fileIcon = require('./assets/images/app_xls.png')
//       break
//     default:
//       fileIcon = require('./assets/images/app_what.png')
//   }
//   return fileIcon
// }

export {
  clone,
  arrayRemoveOne,
  clickElement,
  compress,
  coolingElement,
  freeze,
  isEmptyObject,
  getLocal,
  initMap,
  strToBool,
  getNowFormatDate,
  getDeviceType,
  getQueryString,
  throttle,
  throttle2,
  dataURLtoBlob
}
